<template>
  <div class="filter_list">
    <!-- 头部信息 -->
    <div class="filter_top">
      <span class="filter_title">筛选条件列表</span>
      <a-button type="primary" class="button_style" @click="add_filter" icon="plus">
        新建
      </a-button>
    </div>
    <!-- 表格 -->
    <a-table 
      :columns="columns" 
      :data-source="filterTable" 
      :pagination="false"
      :loading="table_loading"
      rowKey="id"
      size="middle"
    >
      <span slot="action" slot-scope="row">
        <a @click="update_filter(row)">编辑</a>
        <a-divider type="vertical" />
        <a @click="delete_filter(row)">删除</a>
      </span>
    </a-table>
    <!-- 抽屉 -->
    <a-drawer
      class="filter_list_drawer"
      :title="title"
      placement="right"
      :maskClosable="false"
      :visible="drawer"
      width="50%"
      @close="onClose"
    >
      <div class="drawer_form">
        <a-form-model
          ref="ruleForm"
          :model="form"
          :rules="rules"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 19 }"
        >
          <a-form-model-item label="筛选字段名称" prop="name">
            <a-input v-model="form.name" placeholder="请输入筛选字段名称"/>
          </a-form-model-item>
          <a-form-model-item label="控件类型" prop="type">
            <a-select v-model="form.type" placeholder="请选择控件类型" @change='handleType'>
              <a-select-option value="input">
                文本输入框
              </a-select-option>
              <a-select-option value="select">
                单选下拉框
              </a-select-option>
              <a-select-option value="selects">
                多选下拉框
              </a-select-option>
              <a-select-option value="date-range">
                日期范围
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="筛选字段映射" v-if="form.type != 'date-range'"  >
            <a-table :columns="formColumns" :data-source="mapTable" :pagination="false" :bordered="false">
               <template slot="operation" slot-scope="text, record, index">
                  <a-popconfirm
                    title="确定删除吗?"
                    @confirm="() => onDelete(index)"
                  >
                    <a href="javascript:;">删除</a>
                  </a-popconfirm>
                </template>
            </a-table>
            <div class="add_table_columns">
              <a-button icon="plus" style="width: 100%;" type="dashed" @click="add_map_filter">添加</a-button>
            </div>
            <span class="map_content" v-show="map_field">请配置完整的筛选映射字段</span>
          </a-form-model-item>
          <a-modal v-model="visible1" title="添加筛选字段映射" @ok="handleOk">
            <a-form-model
              ref="mapForm"
              :model="mapForm"
              :rules="mapRules"
              :label-col="{ span: 5 }"
              :wrapper-col="{ span: 17 }"
            >
              <a-form-model-item label="数据集" prop="datasetId">
                <a-select v-model="mapForm.datasetId" @change="handleChange">
                  <a-select-option v-for="(item, index) in data_set" :key="index" :value="item.id" >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
              <a-form-model-item label="筛选字段" prop="filterName">
                <a-select v-model="mapForm.filterName">
                  <a-select-option v-for="(it,idx) in render_filter" :key="idx" :value="it.name" :disabled="it.disabled">
                    {{ it.displayName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-form-model>
          </a-modal>
          <a-form-model-item label="字段映射(开始日期)" v-if="form.type == 'date-range'"  >
            <a-table :columns="formColumns" :data-source="startTable" :pagination="false" :bordered="false">
               <template slot="operation" slot-scope="text, record, index">
                  <a-popconfirm
                    title="确定删除吗?"
                    @confirm="() => onDeleteStart(index)"
                  >
                    <a href="javascript:;">删除</a>
                  </a-popconfirm>
                </template>
            </a-table>
            <div class="add_table_columns">
              <a-button icon="plus" style="width: 100%;" type="dashed" @click="add_start_filter">添加</a-button>
            </div>
            <span class="map_content" v-show="map_field">请配置完整的筛选映射字段</span>
          </a-form-model-item>
          <a-modal v-model="visible2" title="添加筛选字段映射(开始日期)" @ok="startHandleOk">
            <a-form-model
              ref="startForm"
              :model="mapForm"
              :rules="mapRules"
              :label-col="{ span: 5 }"
              :wrapper-col="{ span: 19 }"
            >
              <a-form-model-item label="数据集" prop="datasetId">
                <a-select v-model="mapForm.datasetId" @change="handleChange">
                  <a-select-option v-for="(item, index) in data_set" :key="index" :value="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
              <a-form-model-item label="筛选字段" prop="filterName">
                <a-select v-model="mapForm.filterName">
                  <a-select-option v-for="(it,idx) in render_filter" :key="idx" :value="it.name" :disabled="it.disabled">
                    {{ it.displayName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-form-model>
          </a-modal>
          <a-form-model-item label="字段映射(结束日期)" v-if="form.type == 'date-range'"  >
            <a-table :columns="formColumns" :data-source="endTable" :pagination="false" :bordered="false">
               <template slot="operation" slot-scope="text, record, index">
                  <a-popconfirm
                    title="确定删除吗?"
                    @confirm="() => onDeleteEnd(index)"
                  >
                    <a href="javascript:;">删除</a>
                  </a-popconfirm>
                </template>
            </a-table>
            <div class="add_table_columns">
              <a-button icon="plus" style="width: 100%;" type="dashed" @click="add_end_filter">添加</a-button>
            </div>
            <span class="map_content" v-show="map_field">请配置完整的筛选映射字段</span>
          </a-form-model-item>
          <a-modal v-model="visible3" title="添加筛选字段映射(结束日期)" @ok="endHandleOk">
            <a-form-model
              ref="endForm"
              :model="mapForm"
              :rules="mapRules"
              :label-col="{ span: 5 }"
              :wrapper-col="{ span: 19 }"
            >
              <a-form-model-item label="数据集" prop="datasetId">
                <a-select v-model="mapForm.datasetId" @change="handleChange">
                  <a-select-option v-for="(item, index) in data_set" :key="index" :value="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
              <a-form-model-item label="筛选字段" prop="filterName">
                <a-select v-model="mapForm.filterName">
                  <a-select-option v-for="(it,idx) in render_filter" :key="idx" :value="it.name" :disabled="it.disabled">
                    {{ it.displayName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-form-model>
          </a-modal>
          <a-form-model-item label="默认值(可选)" prop="defaultValue"  v-if="form.type != 'date-range'"  >
            <a-textarea v-model="form.defaultValue" placeholder="请输入默认值" @change="onDefaultChange" />
            <span class="map_content" v-show="default_rule">默认值最大长度为255位</span>
          </a-form-model-item>
          <a-form-model-item label="默认值(可选)" prop="defaultValue"  v-if="form.type == 'date-range'"  >
            <a-switch class="time_jump" checked-children="动" un-checked-children="静" v-model="switchStatus" @change="onSwitchChange" />
            <a-range-picker v-model="defaultTime" @change="onDateChange" />
          </a-form-model-item>
        </a-form-model>
      </div>
      <div class="drawer_divider">
        <a-divider />
        <div class="steps-action">
          <a-button @click="onClose"  style="margin-right: 8px;">
            取消
          </a-button>
          <a-button
            type="primary"
            @click="save_filter_drawer"
            :loading="load_button"
          >
            确定
          </a-button>
        </div>
      </div>
    </a-drawer>
  </div>
</template>

<script>
const columns = [
  { 
    title: '筛选条件名称', 
    dataIndex: 'name', 
  },
  { 
    title: '类型', 
    dataIndex: 'type', 
  },
  { title: '默认值', dataIndex: 'defaultValue' },
  {
    title: '操作',
    fixed: 'right',
    scopedSlots: { customRender: 'action' },
  }
]

const formColumns = [
  {
    title: '数据集',
    dataIndex: 'datasetId',
    scopedSlots: { customRender: 'datasetId' },
  },
  {
    title: '筛选字段',
    dataIndex: 'filterName',
    scopedSlots: { customRender: 'filterName' },
  },
  {
    title: '操作',
    dataIndex: 'operation',
    scopedSlots: { customRender: 'operation' },
  }
]
import { mapActions, mapState } from 'vuex'
  export default {
    data() {
      return {
        _this: this,
        dataList: [],
        columns,
        drawer: false,
        title: '新建筛选条件',
        load_button: false,
        formColumns,
        form: {},
        config: [],
        date_obj: {
          start: [],
          end: []
        },
        rules: {
          name: [{ required: true, message: '请输入筛选条件名称', tigger: 'blur' }, { max: 20, message: '最大输入为20个字符', tigger: 'blur' }],
          type: [{ required: true, message: '请选择类型', tigger: 'change' }],
        },
        data_set: [],
        filter_field: {
          datasetId: null,
          filter: []
        },
        switchStatus: false,
        dataset_list: [],
        map_field: false,
        default_rule: false,
        visible1: false,
        visible2: false,
        visible3: false,
        table_loading: false,
        filter_list: [],
        mapForm: {
          datasetId: '',
          filterName: ''
        },
        mapRules: {
          datasetId: [
            { required: true, type: 'number', message: '请选择数据集', tigger: 'change' }
          ],
          filterName: [
            { required: true, message: '请选择筛选字段', tigger: 'change' }
          ]
        },
        defaultTime: []
      }
    },
    watch: {
      drawer (val) {
        if (!val) {
          this.form = {}
          this.config = []
          this.date_obj = {
            start: [],
            end: []
          }
          this.defaultTime = null
          this.$refs.ruleForm && this.$refs.ruleForm.clearValidate()
        }
      },

      visible1 (val) {
        if (!val) {
          this.mapForm = {}
          this.$refs.mapForm && this.$refs.mapForm.clearValidate()
        }
      },
      visible2 (val) {
        if (!val) {
          this.mapForm = {}
          this.$refs.startForm && this.$refs.startForm.clearValidate()
        }
      },
      visible3 (val) {
        if (!val) {
          this.mapForm = {}
          this.$refs.endForm && this.$refs.endForm.clearValidate()
        }
      }
    },
    filters:{

    },
    computed: {
      ...mapState('custom', ['report', 'reportForm']),
      ...mapState('filter', ['filterList']),
      render_filter () {
          let arr = []
          if (this.form.type == 'date-range') {
              if (this.visible2) {
                  this.filter_field.filter.forEach((filter,index) =>{
                      let newFilter = {...JSON.parse(JSON.stringify(filter)), disabled: false}
                      this.date_obj.start.forEach(item => {
                          if (item.filterName==filter.name && item.datasetId == this.filter_field.datasetId) {
                              newFilter.disabled = true
                          }
                      })
                      arr.push(newFilter)
                  })
              }
              if (this.visible3) {
                this.filter_field.filter.forEach((filter,index) =>{
                    let newFilter = {...JSON.parse(JSON.stringify(filter)), disabled: false}
                    this.date_obj.end.forEach(item => {
                        if (item.filterName==filter.name && item.datasetId == this.filter_field.datasetId) {
                            newFilter.disabled = true
                        }
                    })
                    arr.push(newFilter)
                })
              }
          } else {
            this.filter_field.filter.forEach((filter,index) =>{
                let newFilter = {...JSON.parse(JSON.stringify(filter)), disabled: false}
                this.config.forEach(item => {
                    if (item.filterName == filter.name && item.datasetId == this.filter_field.datasetId) {
                        newFilter.disabled = true
                    }
                })
                arr.push(newFilter)
            })
          }
          return arr
      },
      filterTable () {
        return this.filterList.map(item =>{
          let type = ''
          if (item.type == 'input') {
            type = '输入'
          } else if (item.type == 'select') {
            type = '单选'
          } else if (item.type == 'selects') {
            type = '多选'
          } else if (item.type == 'date-range') {
            type = '日期'
          }
          let defaultValue = ''
          let df = item.type == 'date-range' ? JSON.parse(item.defaultValue) : item.defaultValue
          if (item.defaultValue && item.type == 'date-range') {
            if (df.type == 'relative' && item.defaultValue) {
              let time = df.values.split(',')
              if (time[0] == time[1] && time[0] != 0 && time[1] != 0) {
                defaultValue = `${time[0]} 天前（动态）`
              } else if (time[0] == 0 && time[1] == 0) {
                defaultValue = `当天（动态）`
              } else if (time[0] == 0 && time[1]<0) {
                defaultValue = `未来 ${time[0]-time[1]} 天（动态）`
              } else {
                if (time[1] == 0) {
                  defaultValue = `最近 ${time[0]*1 + 1} 天（动态）`
                }else {
                  if(time[0] > time[1]) {
                    defaultValue = `最近 ${time[1]}-${time[0]} 天（动态）`
                  } else {
                    defaultValue = `最近 ${time[0]}-${time[1]} 天（动态）`
                  }
                }
              }
            }else if(df.type == 'absolute' && item.defaultValue) {
              defaultValue = `${df.values[0]}至${df.values[1]}（静态）`
            } else {
              defaultValue = ''
            }
          } else {
            defaultValue = df
          }
          return {...item, type, defaultValue}
        })
      },
      startTable () {
        let config = JSON.parse(JSON.stringify(this.date_obj.start)),
            dataset = JSON.parse(JSON.stringify(this.dataset_list)),
            filter = JSON.parse(JSON.stringify(this.filter_list)),
            table = []
        for (let i=0; i<config.length; i++) {
          for (let j=0; j<dataset.length; j++) {
            for (let k=0; k<filter.length; k++) {
              if (config[i].datasetId == dataset[j].id) {
                if (config[i].filterName == filter[k].name) {
                  table.push({
                    ...config[i],
                    datasetId: dataset[j].name,
                    filterName: filter[k].displayName
                  })
                }
              }
            }
          }
        }
        return table
      },
      endTable () {
        let config = JSON.parse(JSON.stringify(this.date_obj.end)),
            dataset = JSON.parse(JSON.stringify(this.dataset_list)),
            filter = JSON.parse(JSON.stringify(this.filter_list)),
            table = []
        for (let i=0; i<config.length; i++) {
          for (let j=0; j<dataset.length; j++) {
            for (let k=0; k<filter.length; k++) {
              if (config[i].datasetId == dataset[j].id) {
                if (config[i].filterName == filter[k].name) {
                  table.push({
                    ...config[i],
                    datasetId: dataset[j].name,
                    filterName: filter[k].displayName
                  })
                }
              }
            }
          }
        }
        return table
      },
      mapTable () {
        let config = JSON.parse(JSON.stringify(this.config)),
            dataset = JSON.parse(JSON.stringify(this.dataset_list)),
            filter = JSON.parse(JSON.stringify(this.filter_list)),
            table = []
        for (let i=0; i<config.length; i++) {
          for (let j=0; j<dataset.length; j++) {
            for (let k=0; k<filter.length; k++) {
              if (config[i].datasetId == dataset[j].id) {
                if (config[i].filterName == filter[k].name) {
                  table.push({
                    ...config[i],
                    datasetId: dataset[j].name,
                    filterName: filter[k].displayName
                  })
                }
              }
            }
          }
        }
        return table
      },
    },
    methods: {
      ...mapActions('filter', ['getFilterData', 'deleteFilter', 'get_update_id', 'set_new_filter', 'updateFilter']),
      ...mapActions('custom', ['getDsList']),
      ...mapActions('dataManage', ['getAllDataSourceList']),
      add_filter () {
        this.title = '新建筛选条件'
        this.drawer = true;
      },
      update_filter (row) {
        this.title = '编辑筛选条件'
        this.drawer = true
        this.get_update_id({id: row.id, reportId: row.reportId})
          .then(res => {
            this.form = { ...res.data, config: JSON.parse(res.data.config), defaultValue:res.data.type == 'date-range' ? JSON.parse(res.data.defaultValue) : res.data.defaultValue }
            if ( this.form.type == 'date-range' ) {
              this.date_obj.start = [...this.form.config.start]
              this.date_obj.end = [...this.form.config.end]
              if (this.form.defaultValue) {
                if (this.form.defaultValue.type == 'relative') {
                  this.switchStatus = true
                  let defaultValue = this.form.defaultValue.values.split(',')
                  this.defaultTime = [this.moment().subtract(parseInt(defaultValue[0]), 'days').format('YYYY-MM-DD'), this.moment().subtract(parseInt(defaultValue[1]), 'days').format('YYYY-MM-DD') ]
                } else {
                  this.switchStatus = false
                  let defaultValue = this.form.defaultValue.values
                  this.defaultTime = [this.moment(defaultValue[0]).format('YYYY-MM-DD'), this.moment(defaultValue[1]).format('YYYY-MM-DD') ]
                }
              }
            } else {
              this.config = [...this.form.config] 
            }
          })
      },
      // 删除映射字段
      onDelete (key) {
        this.config.splice(key, 1)
      },
      onDeleteStart (key) {
        this.date_obj.start.splice(key, 1)
      },
      onDeleteEnd (key) {
        this.date_obj.end.splice(key, 1)
      },
      delete_filter (row) {
        this.$confirm({
          title: '删除提示',
          content: '删除数据后无法恢复，您确定要继续吗？',
          okText: '确定',
          cancelText: '取消',
          onOk: () => {
            this.deleteFilter({id: row.id, reportId: this.$route.query.id})
              .then(res => {
                this.$message.success('筛选条件删除成功！')
                this.getFilterData({id: this.$route.query.id})
              })
              .catch(err => this.$$message.error('筛选条件删除失败，原因：' + err.msg + '！'))
          },
          onCancel: () => {},
        })        
      },
      onDefaultChange () {
        if ( this.form.defaultValue.length > 255) {
          this.default_rule = true
        } else {
          this.default_rule = false
        }
      },
      save_filter_drawer () {
        this.$refs.ruleForm.validate(valid => {
          if (valid) {
            if (this.form.type == 'date-range') {
              if(!this.date_obj.start.length || !this.date_obj.end.length) {
                this.map_field = true
                return
              } else {
                this.map_field = false
              }
              let isTrue = false
              this.date_obj.start.forEach(item => {
                if (!item.datasetId) {
                  this.map_field = true
                  isTrue = true 
                } else {
                  this.map_field = false
                }
                if (!item.filterName) {
                  this.map_field = true
                  isTrue = true 
                } else {
                  this.map_field = false
                }
              })
              this.date_obj.end.forEach(item => {
                if (!item.datasetId) {
                  this.map_field = true
                  isTrue = true 
                } else {
                  this.map_field = false
                }
                if (!item.filterName) {
                  this.map_field = true
                  isTrue = true 
                } else {
                  this.map_field = false
                }
              })
              if (isTrue) return
            } else {
              if(!this.config.length) {
                this.map_field = true
                return 
              } else {
                this.map_field = false
              }
              let isTrue = false
              this.config.forEach(item => {
                if(!item.datasetId) {
                  this.map_field = true
                  isTrue = true 
                } else {
                  this.map_field = false
                }
                if (!item.filterName) {
                  this.map_field = true
                  isTrue = true 
                } else {
                  this.map_field = false
                }
              })
              if (isTrue) return
            }
            if ( this.default_rule ) {
              return
            }

            if (this.form.type =='date-range') {
              this.date_obj.start.forEach((item, idx) =>{
                delete this.date_obj.start[idx].key
                delete this.date_obj.start[idx].editable
              })
              this.date_obj.end.forEach((item, idx) =>{
                delete this.date_obj.end[idx].key
                delete this.date_obj.end[idx].editable
              })
              this.form.config = {...this.date_obj}
              if (!this.defaultTime.length) {
                this.$message.error('请选择完整的日期');
                return
              }
            } else {
              this.config.forEach((item, idx) =>{
                delete this.config[idx].key
                delete this.config[idx].editable
              })
              this.form.config = [...this.config]
            }
            if (this.form.type == 'select') {
              let test_datasource = false
              this.form.config.forEach(item => {
                if (this.test_jdbc(item.datasetId)) {
                  test_datasource = true
                }
              })
              if (test_datasource) {
                if (!this.form.defaultValue) {
                  this.$message.error('筛选条件包含sql，必须设置默认值')
                  return
                }
              }
            }
            this.load_button = true
            if (this.form.id) {
              this.updateFilter({...this.form, config: JSON.stringify(this.form.config),defaultValue: this.form.type == 'date-range' ? JSON.stringify(this.form.defaultValue) : this.form.defaultValue, reportId: this.$route.query.id})
                .then(res => {
                  this.drawer = false
                  this.$message.success('筛选条件编辑成功！')
                  this.getFilterData({id: this.$route.query.id})
                })
                .catch(err => {
                  this.$message.error('筛选条件编辑失败，原因：' + err.msg + '！')
                })
                .finally(_=>{
                  this.load_button = false
                })
            } else {
              this.set_new_filter({...this.form, config: JSON.stringify(this.form.config),defaultValue: this.form.type == 'date-range' ? JSON.stringify(this.form.defaultValue) : this.form.defaultValue, reportId: this.$route.query.id })
                .then(res => {
                  this.drawer = false
                  this.$message.success('筛选条件创建成功！')
                  this.getFilterData({id: this.$route.query.id})
                })
                .catch(err => {
                  this.$message.error('筛选条件创建失败，原因：' + err.msg + '！')
                })
                .finally(_=>{
                  this.load_button = false
                })
            }
          } else {
            return false
          }
        });
        
      },
      onSwitchChange (status) {
        this.switchStatus = status
        this.form.defaultValue.type = status ? 'relative' : 'absolute';
        if (this.form.defaultValue.values) {
            if (this.form.defaultValue.values instanceof Array) {
                if (status) {
                    let start =  this.form.defaultValue.values[0],
                        end = this.form.defaultValue.values[1],
                        values = `${this.moment().diff(this.moment(start), 'days')},${this.moment().diff(this.moment(end), 'days')},day`;
                    this.$set(this.form.defaultValue, 'values', values);
                }
            } else {
                if (!status) {
                    let defaultValue = this.form.defaultValue.values.split(',')
                    let values = [this.moment().subtract(parseInt(defaultValue[0]), 'days').format('YYYY-MM-DD'), this.moment().subtract(parseInt(defaultValue[1]), 'days').format('YYYY-MM-DD') ]
                    this.$set(this.form.defaultValue, 'values', values);
                }
            }
        }
      },
      onDateChange (date, dateString) {
        let defaultValue = null
        if (this.switchStatus) {
          const start = dateString[0], 
                end = dateString[1],
                values = `${this.moment().diff(this.moment(start), 'days')},${this.moment().diff(this.moment(end), 'days')},day`;
          defaultValue = values
        } else {
          this.form.defaultValue.type = 'absolute';
          defaultValue = dateString
        }
        this.form.defaultValue.values = defaultValue
      },
      test_jdbc (datasetId) {
        let datasourceId = null
        this.dataset_list.forEach(data => {
          if (data.id == datasetId) {
            datasourceId = data.datasourceId
          }
        })
        let datasource = null
        this.dataList.forEach(data => {
          if (data.id == datasourceId) {
            datasource = data
          }
        })
        if(datasource && datasource.type == 1) {
          return true
        } else {
          return false
        }
      },
      onFilterChange(datasetId) {
        let arr = []
        this.dataset_list.forEach(data => {
          if (data.id == datasetId) {
            arr = data.filter
          }
        })
        return arr
      },
      // 数据集改变复选框事件
      handleChange(value) {
        // 判断数据源类型 true 为jdbc
        this.filter_field.datasetId = value;
        this.filter_field.filter = [];
        if (this.test_jdbc(value)) {
            this.filter_field.filter = this.onFilterChange(value).filter(item=>{
              if (this.form.type == 'input' || this.form.type == 'date-range') {
                if (item.type == 'input') return item
              }
              if (this.form.type == 'select') {
                if (item.type == 'select') return item
              }
            })
        } else {
          this.filter_field.filter = this.onFilterChange(value).filter(item => {
            if (this.form.type == 'input' || this.form.type == 'date-range') {
              if (item.type == 'input') return item
            }else if(this.form.type == 'select' || this.form.type == 'selects') {
              if (item.type == 'select') return item
            }
          })
        }
      },
      // 选择控件类型
      handleType () {
        if (this.form.type == 'date-range') {
          this.form.defaultValue = {}
        } else {
          this.form.defaultValue = null
        }
        // this.data_set = this.dataset_list.map(item=>item)
      },
      // 添加映射字段
      add_map_filter (timer) {
        this.visible1 = true
      },
      add_start_filter () {
        this.visible2 = true
      },
      add_end_filter () {
        this.visible3 = true
      },
      handleOk () {
        this.$refs.mapForm.validate(valid => {
          if (valid) {
            this.config.push(JSON.parse(JSON.stringify({...this.mapForm, key: this.mapForm.filterName+'-'+this.mapForm.datasetId})))
            this.visible1 = false
          }
        })
      },
      startHandleOk () {
        this.$refs.startForm.validate(valid => {
          if (valid) {
            this.date_obj.start.push(JSON.parse(JSON.stringify({...this.mapForm, key: this.mapForm.filterName+this.mapForm.datasetId})))
            this.visible2 = false
          }
        })
      },
      endHandleOk () {
        this.$refs.endForm.validate(valid => {
          if (valid) {
            this.date_obj.end.push(JSON.parse(JSON.stringify({...this.mapForm, key: this.mapForm.filterName+this.mapForm.datasetId})))
            this.visible3 = false
          }
        })
      },
      // 点击取消或关闭按钮
      onClose () {
        this.drawer = false
        // this.$confirm({
        //   title: '提示',
        //   content: '关闭后数据会丢失，确定关闭吗？',
        //   okText: '确定',
        //   cancelText: '取消',
        //   onOk: () => {
        //     this.drawer = false
        //   },
        //   onCancel: () => {},
        // })
      },
      // 初始化页面
      loadFilterList () {
        this.table_loading = true;
        this.getFilterData({id: this.$route.query.id})
          .then(res => {
            this.getDsList({id: this.$route.query.id})
              .then(res=>{
                const {data} = res
                this.dataset_list = data.map(item=>{
                  if (item.type == 0) {
                    return {...item, config: item.config, filter: JSON.parse(item.filter), output: JSON.parse(item.output)}
                  } else {
                    return {...item, config: JSON.parse(item.config), filter: JSON.parse(item.filter), output: JSON.parse(item.output)}
                  }
                })
                this.data_set = this.dataset_list.map(item=>item)
                let arr = this.dataset_list.map(item => item.filter)
                arr = arr.flat(Infinity)
                arr.forEach(item => {
                  if (this.filter_list.indexOf(JSON.stringify(item)) == -1) {
                    this.filter_list.push(JSON.stringify(item))
                  }
                })
                this.filter_list = this.filter_list.map(item=>{
                  return JSON.parse(item)
                })
              })
          })
          .catch(err => {
            this.$message.error('获取筛选条件列表失败，原因：'+ err.msg + '！')
          })
          .finally(res => {
            this.table_loading = false;
          })
        this.getAllDataSourceList()
          .then(res => {
            this.dataList = res.data.data;
          })
      }
    },
    mounted () {
      this.loadFilterList()
    }
  }
</script>

<style scoped>
.filter_list,
.filter_top {
  width: 100%;
}

.filter_top {
  display: inline-block;
  margin-bottom: 22px;
}

.filter_top>>>.button_style {
  float: right;
}

.filter_title {
  float: left;
  font-size: 16px;
  font-weight: 500;
  color: rgba(0, 0, 0, .85);
  line-height: 32px;
}

.filter_list>>>.ant-drawer-wrapper-body {
  display: flex;
  flex-direction: column;
}

.filter_list>>>.ant-drawer-body {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.drawer_form {
  height: 770px;
  overflow: auto;
}

.steps-action{
  float: right;
}

.editable-row-operations a {
  margin-right: 8px;
}

.map_content {
  color: #f5222d;
}

.filter_list_drawer >>> .ant-drawer-body {
  height: calc(100% - 55px);
  display: flex;
  flex-direction: column;
  padding: 24px 24px 12px;
}

button.time_jump {
  margin: 0px 10px !important;
}

.drawer_divider >>> .ant-divider-horizontal {
  margin: 12px 0px !important;
}
</style>